package uk.co.cocking.getinline2.pipeline.io;

import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.List;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import uk.co.cocking.getinline2.pipeline.transformers.AbstractTransformer;

public class XsltTransformer extends AbstractTransformer<String, String> {
	

	private javax.xml.transform.Transformer xsltTransformer = null;

	public XsltTransformer(File styleSheet) {
		Source xsltSource = new StreamSource(styleSheet);
		TransformerFactory factory = TransformerFactory.newInstance();
		try {
			xsltTransformer = factory.newTransformer(xsltSource);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<String> transform(String incomingItem)
			throws CouldNotProcessRecordException {
		Source xmlSource = new StreamSource(new StringReader(incomingItem));
		StringWriter stringWriter = new StringWriter();
		Result outputTarget = new StreamResult(stringWriter);
		try {
			xsltTransformer.transform(xmlSource, outputTarget);
		} catch (TransformerException e) {
			throw new CouldNotProcessRecordException("could not transform "+incomingItem, e);
		}
		return enlist(stringWriter.toString());
	}

}
